package game.log;

import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Calendar;

/**
 * Logger keeps a log file.
 */
public class Logger {

   private static final String DATE_FORMAT = "yyyy-MM-dd HH:mm:ss";
   private static FileWriter fileWriter;
   private static BufferedWriter out;
   private static boolean init = false;
   
   public static void init() {
      try {
         fileWriter = new FileWriter(System.currentTimeMillis() + ".log");
      } catch (IOException e) { }
      out = new BufferedWriter(fileWriter);
      init = true;
      write("SERVER STARTED");
   }
   
   public static void write(String msg) {
      synchronized (out) {
         if (!init) init();
         System.out.println(msg);
         try {
            out.write(now() + " " + msg + "\n");
            out.flush();
         } catch (IOException e) { }
      }
   }
   
   private static String now() {
      Calendar cal = Calendar.getInstance();
      SimpleDateFormat sdf = new SimpleDateFormat(DATE_FORMAT);
      return sdf.format(cal.getTime());
   }
}
